#include "common/include/stock_common.h"
#include "common/include/stock_timesync.h"

static int
stock_timesync_parse(stock_timesync_msg *msg, stock_timesync *ts)
{
    if (stock_verify_header(msg) != 0) {
        return -1;
    }

    ts->delta = ntohl(msg->timesync.delta);
    return 0;
}


int
stock_timesync_send(int sock, stock_update *upd) 
{
    char                server_buf[STOCK_TIMESYNC_MSG_SIZE];
    stock_timesync_msg *msg;
    int                 msgsize;
    int                 delta;
    uint32_t            now;

    memset(server_buf, 0, STOCK_TIMESYNC_MSG_SIZE);
    msg = (stock_timesync_msg *) server_buf; 
    msgsize = sizeof(stock_timesync_msg);

    memset(msg->header, 0xFF, STOCK_HEADER_LEN);

    now = stock_gettimeofday();
    delta = now - upd->data.timestamp;
    msg->timesync.delta = htonl(delta);

    if (send(sock, msg, msgsize, 0) < 0) {
        warning("timesync send failed");
        return -1;
    }

    return 0;



    return 0;
}


int
stock_timesync_recv(int sock, stock_timesync *sync) 
{
    struct sockaddr_in  client;
    socklen_t           client_len;
    char                client_buf[STOCK_TIMESYNC_MSG_SIZE];
    stock_timesync_msg *msg;
	char               *pmsg;
    int                 rc;

    msg = (stock_timesync_msg *) client_buf; 
	pmsg = (char *) msg;

    memset(sync, 0, sizeof(stock_timesync));
    memset(client_buf, 0, STOCK_TIMESYNC_MSG_SIZE);

    rc = recvfrom(sock, pmsg, STOCK_TIMESYNC_MSG_SIZE, 0, 
                 (struct sockaddr*) &client, &client_len);

    if (rc == STOCK_TIMESYNC_MSG_SIZE) {  
        if (stock_timesync_parse(msg, sync) != 0) {
            return -1;
        }
    }

    return 0;
}
